package com.thy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.common.base.Result;
import com.hospital.common.base.ThreadAttributes;
import com.hospital.common.dto.management.module.DoctorInfoDto;
import com.hospital.common.enums.ResultStatus;
import com.hospital.common.enums.RoleType;
import com.hospital.common.pojo.TUser;
import com.hospital.common.utils.ThreadLocalUtils;
import com.thy.exception.PatientInfoServiceException;
import com.thy.exception.enums.PatientInfoServiceExpCode;
import com.thy.feign.DataSimulationFeign;
import com.thy.mapper.TUserMapper;
import com.thy.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService {

    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private DataSimulationFeign dataSimulationFeign;
    @Override
    public Long allDoctorCount() {
        LambdaQueryWrapper<TUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TUser::getRole, RoleType.DOCTOR.value);
        return tUserMapper.selectCount(queryWrapper);
    }
    public Long allPatientCount() {
        LambdaQueryWrapper<TUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TUser::getRole, RoleType.PATIENT.value);
        return tUserMapper.selectCount(queryWrapper);
    }

    @Override
    public void updateUser(DoctorInfoDto doctorInfoDto) {
        ThreadAttributes threadAttributes = ThreadLocalUtils.get();
        if(ObjectUtils.isEmpty(threadAttributes)){
            throw new PatientInfoServiceException(PatientInfoServiceExpCode.USER_NOT_EXIST);
        }
        if(!threadAttributes.getRoleType().equals(RoleType.DOCTOR.value)){
            throw new PatientInfoServiceException(PatientInfoServiceExpCode.USER_ROLE_NOT_MATCH);
        }
        TUser tUser = new TUser();
        tUser.setId(threadAttributes.getUserId());
        tUser.setName(doctorInfoDto.getName());
        tUser.setPhone(doctorInfoDto.getPhone());
        tUser.setSex(doctorInfoDto.getSex());
        Result<?> result = dataSimulationFeign.updateUser(tUser);
        if(!result.getCode().equals(ResultStatus.SUCCESS.getCode())){
            throw new PatientInfoServiceException(PatientInfoServiceExpCode.UPDATE_USER_FAILED);
        }
    }
}
